<?php

namespace app\api\controller;

use app\admin\model\Alibaba;
use app\admin\model\Alipay;
use app\admin\model\Banner;
use app\admin\model\Category;
use app\admin\model\Cooperation;
use app\admin\model\Coupon;
use app\admin\model\Feedback;
use app\admin\model\Goods;
use app\admin\model\IndexMenu;
use app\admin\model\Recharge as RechargeModel;
use app\admin\model\RechargeOrder;
use app\admin\model\Station;
use app\admin\model\UserCoupon;
use app\admin\model\Wechat;
use app\common\controller\Frontend;
use think\Collection;
use think\db\BaseQuery;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;

class Recharge extends Frontend
{
    /**
     * @var RechargeModel
     */
    private $model;

    public function initialize()
    {
        parent::initialize();
        $this->model = new RechargeModel();
    }

    /**
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getList()
    {
        $time = time();
        $page = (int)$this->request->get('page', 1);
        $page = $page <= 0 ? 1 : $page;
        $limit = (int)$this->request->get('limit', 10);
        $limit = $limit <= 0 ? 10 : $limit;
        $list = $this->model
            ->whereRaw("start < {$time} or start = 0")
            ->whereRaw("end > {$time} or end = 0")
            ->where('switch', 1)
            ->order('weight desc, id desc')
            ->page($page)
            ->limit($limit)
            ->hidden(['delete_time', 'createtime', 'updatetime', 'switch', 'weight'])
            ->select()
            ->each(function ($item) {
                return $item;
            });
        $this->success('', $list);
    }

    /**
     * @param $id
     * @param $payway
     * @param $channel
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function recharge($id, $payway, $channel)
    {
        $recharge = $this->model->where('switch', 1)->where('id', $id)->find();
        if (!$recharge || $recharge->isEmpty() || $recharge['switch'] != 1) {
            $this->error('数据不存在');
        }
        $start = strtotime($recharge->start);
        $end = strtotime($recharge->end);
        if ($start > 0 && $start > time()) {
            $this->error('未到充值时间');
        }
        if ($end > 0 && $end < time()) {
            $this->error('超出充值时间');
        }
        $userInfo = $this->auth->getUser();
        $order = new RechargeOrder();
        $order->order_sn = $order->getOrderSn();
        $order->user_id = $userInfo['id'];
        $order->recharge_id = $recharge->id;
        $order->price = $recharge->recharge_price;
        $order->give_price = $recharge->give_price;
        $order->integral = $recharge->integral;
        $order->save();

        try {
            if ($payway == 'wechat') {
                $wechat = new Wechat();
                $payment = $wechat->payment('充值', $order->order_sn, $order->price, $userInfo['routine_openid'], $channel, 2);
            } elseif ($payway == 'alipay') {
                $wechat = new Alipay();
                $payment = $wechat->payment('充值', $order->order_sn, $order->price, $channel, 2);
            } else {
                throw new ValidateException('支付方式错误');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('', [
            'payment' => $payment ?? [],
        ]);
    }

    /**
     * @param RechargeOrder $order
     * @param $type
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getOrder(RechargeOrder $order, $type)
    {
        $type = (int)$type;
        $page = (int)$this->request->get('page', 1);
        $page = $page <= 0 ? 1 : $page;
        $limit = (int)$this->request->get('limit', 10);
        $limit = $limit <= 0 ? 10 : $limit;
        $list = $order
            ->where('user_id', $this->auth->getUserId())
            ->when(in_array($type, [0, 1, 2]), function (BaseQuery $query) use ($type) {
                if ($type == 1) {
                    $query->where('status', 0);
                } elseif ($type == 2) {
                    $query->where('status', 1);
                }
            })
            ->page($page)
            ->limit($limit)
            ->select();

        $this->success('', $list);
    }
}